package cn.hu.pet.service.impl;

import cn.hu.basic.domain.dto.PetDto;
import cn.hu.basic.util.AjaxResult;
import cn.hu.basic.util.CurrentLoginInfoUtil;
import cn.hu.org.mapper.EmployeeMapper;
import cn.hu.pet.domain.Pet;
import cn.hu.pet.domain.PetDetail;
import cn.hu.pet.mapper.PetDetailMapper;
import cn.hu.pet.mapper.PetMapper;
import cn.hu.pet.service.IPetService;
import cn.hu.basic.service.impl.BaseServiceImpl;
import cn.hu.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Hu
 * @since 2022-12-27
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PetDetailMapper petDetailMapper;


    @Override
    @Transactional
    public void addByPetDto(PetDto petDto, HttpServletRequest request) throws Exception {
        Pet pet = petDto2pet(new Pet(),petDto);
        //设置创建时间
        pet.setCreatetime(new Date());
        //设置状态为下架
        pet.setState(0);
        //设置店铺id
        Logininfo lf = CurrentLoginInfoUtil.currentLoginInfo(request);
        Long shopId = employeeMapper.findByLoginInfoId(lf.getId()).getShopId();
        pet.setShopId(shopId);
        //存进pet表
        petMapper.add(pet);
        Long petId = pet.getId();
        //将详情存进详情表
        PetDetail detail = petDto.getDetail();
        detail.setPetId(petId);
        petDetailMapper.add(detail);
    }

    @Override
    @Transactional
    public void updateByPetDto(PetDto petDto) {
        Pet pet = petMapper.findById(petDto.getId());
        Pet newPet = petDto2pet(pet, petDto);
        //存进pet表
        petMapper.update(newPet);
        //将详情存进详情表
        PetDetail detail = petDto.getDetail();
        detail.setPetId(newPet.getId());
        petDetailMapper.update(detail);
    }

    @Override
    public void onsale(List<Long> ids) {
        petMapper.batchOnsaleByIds(ids,new Date());
    }

    @Override
    public void offsale(List<Long> ids) {
        petMapper.batchOffsaleByIds(ids,new Date());
    }

    public Pet petDto2pet(Pet pet,PetDto petDto){
        pet.setName(petDto.getName());
        pet.setCostprice(petDto.getCostprice());
        pet.setSaleprice(petDto.getSaleprice());
        pet.setResources(petDto.getResources());
        return pet;
    }
}
